package com.study.zzedu.fragment.home;


import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.dreamfish.record.FileUtil;
import com.study.zzedu.R;
import com.study.zzedu.adapter.VideoTabAdapter;
import com.study.zzedu.base.BaseFragment;
import com.study.zzedu.base.BaseView;
import com.study.zzedu.entity.LessonHeaderModel;
import com.study.zzedu.ui.evaluate.EvaluateActivity;
import com.study.zzedu.ui.exercise.view.NoScrollViewPager;
import com.study.zzedu.ui.login.LoginActivity;
import com.study.zzedu.ui.modifypwd.ModifyPwdActivity;
import com.study.zzedu.ui.study.StudyActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.DeviceUtil;
import com.study.zzedu.utils.OkHttpUtils;
import com.study.zzedu.utils.SharedPreferencesHelper;
import com.study.zzedu.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;

/**
 * Created by kiros on 2020/9/5.
 */

public class VideoTabFragment extends BaseFragment<BaseView, VideoTabPresenter> implements BaseView, View.OnClickListener {

    private XTabLayout tabLayout;
    private NoScrollViewPager viewPager;
    private List<String> list;

    private TextView tv_qulity, tv_online, tv_video;
    private TextView totalInfo, ranking, hasOverCourse, learningCourse, toStudy;

    @Override
    protected VideoTabPresenter createPresenter() {
        return new VideoTabPresenter();
    }

    @Override
    protected BaseView createView() {
        return this;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_video_tab;
    }

    @Override
    protected void initView(View view) {
        viewPager = view.findViewById(R.id.viewpager);
        tabLayout = view.findViewById(R.id.tab);

        totalInfo = view.findViewById(R.id.tv_totle_info);
        ranking = view.findViewById(R.id.tv_rank_info);
        hasOverCourse = view.findViewById(R.id.tv_studyed);
        learningCourse = view.findViewById(R.id.tv_studying);
        toStudy = view.findViewById(R.id.tv_to_study);
        tv_video = view.findViewById(R.id.tv_video);
        tv_online = view.findViewById(R.id.tv_online);
        tv_qulity = view.findViewById(R.id.tv_qulity);

        /*初始化数据*/
        list = new ArrayList<>();
        list.add("课程点播");
        list.add("直播课堂");
        list.add("素质教育");
        /*设置Adapter*/
        viewPager.setAdapter(new VideoTabAdapter(getActivity().getSupportFragmentManager(), list));
        /*Tab与ViewPager绑定*/
        tabLayout.setupWithViewPager(viewPager);
        //tabLayout.setVisibility(View.VISIBLE);
        viewPager.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b)
                    pageSwitch(view.getId());
            }
        });

        getPresenter().getDataHeader(view.getContext());
        localBroadcast = new DataUpdataeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstant.ACTION_EVENT_HEAD_DATAUPDATA);
        intentFilter.addAction(AppConstant.ACTION_EVENT_401);

        view.getContext().registerReceiver(localBroadcast, intentFilter);
    }

    @Override
    protected void initData() {
        int screenWidth = DeviceUtil.deviceWidth(getContext());
        int range = screenWidth / 13;
        FrameLayout.LayoutParams fl1 = new FrameLayout.LayoutParams(screenWidth / 3 + screenWidth / 16, FrameLayout.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams fl2 = new FrameLayout.LayoutParams(screenWidth / 3 + screenWidth / 12, FrameLayout.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams fl3 = new FrameLayout.LayoutParams(screenWidth / 3 + screenWidth / 16, FrameLayout.LayoutParams.MATCH_PARENT);
        fl1.gravity = Gravity.LEFT;
        fl2.gravity = Gravity.CENTER;
        fl3.gravity = Gravity.RIGHT;

        tv_video.setLayoutParams(fl1);
        tv_online.setLayoutParams(fl2);
        tv_qulity.setLayoutParams(fl3);


    }
    DataUpdataeReceiver localBroadcast;
    @Override
    protected void initListener() {
        tv_video.setOnClickListener(this);
        tv_online.setOnClickListener(this);
        tv_qulity.setOnClickListener(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        //getActivity().onBackPressed();
    }

    @Override
    public void onClick(View view) {
        pageSwitch(view.getId());
    }

    private void pageSwitch(int viewID) {
        switch (viewID) {
            case R.id.tv_video:
                viewPager.setCurrentItem(0);
                tv_video.setBackgroundResource(R.drawable.video1);
                tv_video.bringToFront();
                tv_online.setBackgroundResource(R.drawable.online2);
                tv_qulity.setBackgroundResource(R.drawable.qulity2);
                break;
            case R.id.tv_online:
                viewPager.setCurrentItem(1);
                tv_online.setBackgroundResource(R.drawable.online1);
                tv_online.bringToFront();
                tv_video.setBackgroundResource(R.drawable.video2);
                tv_qulity.setBackgroundResource(R.drawable.qulity2);
                break;
            case R.id.tv_qulity:
                viewPager.setCurrentItem(2);
                tv_qulity.setBackgroundResource(R.drawable.qulity1);
                tv_qulity.bringToFront();
                tv_video.setBackgroundResource(R.drawable.video2);
                tv_online.setBackgroundResource(R.drawable.online2);
                break;
        }
    }

    @Override
    public void getData(String data) {
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            for (int i = 0; i < jArray.length(); i++) {
                displayData(new LessonHeaderModel(
                        jArray.getJSONObject(i).getString("term"),
                        jArray.getJSONObject(i).getString("termEnd"),
                        jArray.getJSONObject(i).getString("termBegin"),
                        jArray.getJSONObject(i).getInt("totalCourseTime"),
                        jArray.getJSONObject(i).getInt("ranking"),
                        jArray.getJSONObject(i).getInt("hasOverCourse"),
                        jArray.getJSONObject(i).getInt("totalCourseCount"),
                        jArray.getJSONObject(i).getInt("learningCourse"),
                        jArray.getJSONObject(i).getInt("hasScore"),
                        jArray.getJSONObject(i).getInt("totalScore")
                ));
            }
            if (!(jArray.length() > 0)) {
                ToastUtil.showShortToast("header无数据");
                return;
            }
        } catch (Exception e) {
            e.toString();
        }
    }

    @Override
    public void showError(String error) {
    }

    private void displayData(LessonHeaderModel lModel) {

        //String totleTime = String.valueOf(lModel.getTotalCourseTime());
        String totleCourseCount = String.valueOf(lModel.getTotalCourseCount());
        SpannableString textSpanned1 = new SpannableString("共需学习" + totleCourseCount + "门课程");
//        textSpanned1.setSpan(new ForegroundColorSpan(Color.YELLOW),
//                8, 8 + totleTime.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //textSpanned1.setSpan(new AbsoluteSizeSpan(25, true), 8, 8 + totleTime.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textSpanned1.setSpan(new ForegroundColorSpan(Color.YELLOW),
                4 , 4  + totleCourseCount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textSpanned1.setSpan(new AbsoluteSizeSpan(33, true), 4 , 4  + totleCourseCount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        totalInfo.setText(textSpanned1);
        ranking.setText("");
//        if (lModel.getRanking() > 99) {
//            ranking.setVisibility(View.INVISIBLE);
//        } else {
//            ranking.setText("TOP" + lModel.getRanking());
//        }
        hasOverCourse.setText("已学完" + lModel.getHasOverCourse() + "门");
        learningCourse.setText("学习中" + lModel.getLearningCourse() + "门");
        toStudy.setText("待学习" + (lModel.getTotalCourseCount() - lModel.getHasOverCourse() - lModel.getLearningCourse()) + "门");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(localBroadcast != null)
            getContext().unregisterReceiver(localBroadcast);
    }


    private class DataUpdataeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConstant.ACTION_EVENT_HEAD_DATAUPDATA)) {
                getPresenter().getDataHeader(getContext());
            }else if(intent.getAction().equals(AppConstant.ACTION_EVENT_401)){
                SharedPreferencesHelper.getInstance(getContext()).put("loginState", AppConstant.NOT_AUTO_LOGIN);
                AlertDialog.Builder build = new AlertDialog.Builder(getContext());
                build.setTitle("提示").setCancelable(false).setMessage("登录超时，请重新登录！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        getContext().startActivity(new Intent(getContext(), LoginActivity.class));
                        getActivity().finish();
                    }
                }).show();
            }

        }
    }
}
